import { createRouter, createWebHistory } from "vue-router";
import { useAuthStore } from "../stores/auth";
import Chat from "../views/Chat.vue";
import KnowledgeBase from "../views/KnowledgeBase.vue";
import TestMdPreview from "../views/TestMdPreview.vue";
import MarkdownPlayground from "../views/MarkdownPlayground.vue";
import Login from "../views/Login.vue";

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: { requiresAuth: false },
  },
  {
    path: "/",
    name: "Chat",
    component: Chat,
    meta: { requiresAuth: true },
  },
  {
    path: "/knowledge-base",
    name: "KnowledgeBase",
    component: KnowledgeBase,
    meta: { requiresAuth: true },
  },
  {
    path: "/test-md-preview",
    name: "TestMdPreview",
    component: TestMdPreview,
    meta: { requiresAuth: true },
  },
  {
    path: "/markdown-playground",
    name: "MarkdownPlayground",
    component: MarkdownPlayground,
    meta: { requiresAuth: true },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();

  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    // 检查是否已登录
    if (authStore.isAuthenticated) {
      next();
    } else {
      // 未登录，重定向到登录页
      next({
        path: "/login",
        query: { redirect: to.fullPath }, // 保存原始路径，登录后可以跳转回去
      });
    }
  } else {
    // 如果访问登录页且已登录，重定向到首页
    if (to.path === "/login" && authStore.isAuthenticated) {
      next("/");
    } else {
      next();
    }
  }
});

export default router;
